package com.jetpackframework.virtual;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;

public class SkinResource {
    private static SkinResource instance;
    private Resources appResource;
    private String packageName;
    private Resources skinResouce;
    private boolean isDefaultSkin = true;  //是否采用皮肤包中资源 true 不使用 false 使用

    private SkinResource(Context context){
        appResource = context.getResources();
    }
    public static synchronized SkinResource getInstance(Context context) {
        if (instance == null){
            instance = new SkinResource(context);
        }
        return instance;
    }

    public void reset() {
        skinResouce = null;
        packageName = "";
        isDefaultSkin = true;
    }
    public void applyResouce(String packageName, Resources skinResource) {
        this.packageName = packageName;
        this.skinResouce = skinResource;
        isDefaultSkin = TextUtils.isEmpty(packageName) || skinResource == null;
    }
    public int getColor(int resId){
        if (isDefaultSkin){
            return appResource.getColor(resId);
        }
        int identifier = getIdentifier(resId);
        if (identifier != 0){
            return skinResouce.getColor(identifier);
        }
        return appResource.getColor(resId);
    }

    /**
     * 通过宿主中资源ID 获取到皮肤包中的资源ID
     * @param resId
     * @return
     */
    private int getIdentifier(int resId) {
        if (isDefaultSkin) {
            return resId;
        }
        //获取资源的名称和类型
        String resName = appResource.getResourceEntryName(resId);
        String resType = appResource.getResourceTypeName(resId);
        //通过插件的Resources获取到插件中相同名称和类型的id
        return skinResouce.getIdentifier(resName,resType,packageName);
    }

    public Object getBackgroud(int resId) {
        if (isDefaultSkin) {
            return appResource.getDrawable(resId);
        }
        String resourceTypeName = appResource.getResourceTypeName(resId);
        if (resourceTypeName.equals("color")){
            return getColor(resId);
        }else {
            return getDrawable(resId);
        }
    }
    public Drawable getDrawable(int resId) {
        if (isDefaultSkin) {
            return appResource.getDrawable(resId);
        }
        int identifier = getIdentifier(resId);
        if (identifier != 0){
            return skinResouce.getDrawable(identifier);
        }
        return appResource.getDrawable(resId);
    }

    public int getColorStateList(int resId) {
        return 0;
    }
}
